﻿using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
using Resources;
using Service;
using Model;


public partial class EquipmentAdd : System.Web.UI.Page
{
    readonly ReferenceDataService _ReferenceDataService = new ReferenceDataService();
    readonly  StockService  _StockService = new StockService();
    EquipPurchaseInfo _PurchaseInfo  = new EquipPurchaseInfo();
    SparepartPurchaseInfo _SparepartInfo = new SparepartPurchaseInfo();
    ReferenceDataDirectService _ReferenceDataDirectService = new ReferenceDataDirectService();
    private int equipmentId;
    private ListItem[] itemToInsert;
    


    protected void Page_Load(object sender, EventArgs e)
    {

        
        int quantity = !String.IsNullOrEmpty(txtQuantity.Text) ? Int32.Parse(txtQuantity.Text) :0;

        // when equipement
        
        if(!IsPostBack)
        {
            InitialComponent();
            pnlCodeEquipment.Visible = false;
            pnlWarranty.Visible = false;

            pnlSparepart.Visible = false;
          //pnlSoftware.Visible = false;
            LoadSoftwareControl();
        }
       
        
    }
    private void InitializeData(int purchaseQuantity)
    {
        lblQuantity.Text = "There are " + purchaseQuantity + "  item(s) in this purchase item";
        lblPONumber.Text = Session["poNumber"].ToString();

    }
    public void GenerateAvailableCodeNumbers(int purchasedQuantity)
    {
        DataTable _ListSuggestedCodeNumber = new DirectService().GetSuggestedCodeNumbers(purchasedQuantity);
        if (_ListSuggestedCodeNumber.Rows.Count == 0)
        {
            int maxNUM = _StockService.GetMaxEquipmentCodeNumber();
            IList codeNumberList = new UitilityService().GetRangeCodeNumber(maxNUM, purchasedQuantity);
            drlAutoCode.DataSource = codeNumberList;
        }
        else
        {
            drlAutoCode.DataSource = _ListSuggestedCodeNumber;
            drlAutoCode.DataTextField = "SuggestedNumber";
            drlAutoCode.DataValueField = "SuggestedNumber";
            drlAutoCode.DataBind();
        }
    }
    
    private void InitialComponent()
    {
        drlSupplier.DataSource = _ReferenceDataService.GetSuppliers();
        drlSupplier.DataValueField = Resource.SupplierValueField;
        drlSupplier.DataTextField = Resource.SupplierTextField;
        drlSupplier.DataBind();

        drlEquipmentType.DataSource = _ReferenceDataService.GetEquipmentTypes(chkSparepart.Checked);
        drlEquipmentType.DataValueField = Resource.EquipmentTypeValueField;
        drlEquipmentType.DataTextField = Resource.EquipmentTypeTextField;
        drlEquipmentType.DataBind();
        
    }
    public void btnValidate_Click(object sender, EventArgs e)
    {
        if (!new Utility().TestPermissions(Resource.PermissionAddEquipment))
        {
            lblpermissionAdd.Text = Resource.Permission;
            return;
        }

        lblpermissionAdd.Visible = false;

        Session["defaultTabIndex"] = 1;
        if (!ValidateData())
        {
            Session["purchaseId"] = null;
            return;
        }
        lblRequiredCompany.Visible = false;
        if (chkSparepart.Checked)
        {

            _SparepartInfo = GetSparePartPurchaseInfo();
            GenerateTypeModel();
            _StockService.InsertSparepartInfo(_SparepartInfo);
            _StockService.InsertSparepart(GetSparePart(_SparepartInfo.SparepartPurchaseInfoId));

           
            Session["purchaseId"] = _SparepartInfo.SparepartPurchaseInfoId.ToString();
            Session["quantity"] = _SparepartInfo.Quantity.ToString();

            pnlSparepart.Visible = false;
            pnlCodeEquipment.Visible = false;
            //pnlSoftware.Visible = false;

        }
        else
        {
            _PurchaseInfo = GetEquipPurchaseInfo();
            _StockService.InsertPurchaseInfo(_PurchaseInfo);
            if (_ReferenceDataDirectService.GetComputerId() == Int32.Parse(drlEquipmentType.SelectedValue))
            {
                _SparepartInfo = GetSparePartPurchaseInfo();
                GenerateTypeModel();
                _StockService.InsertSparepartInfo(_SparepartInfo);
                _StockService.InsertSparepart(GetSparePart(_SparepartInfo.SparepartPurchaseInfoId));
                Session["purchaseId"] = _SparepartInfo.SparepartPurchaseInfoId.ToString();
                Session["quantity"] = _SparepartInfo.Quantity.ToString();

                pnlSparepart.Visible = true;
                //pnlSoftware.Visible = true;

            }
            else
            {
                pnlSparepart.Visible = false;
                //pnlSoftware.Visible = false;
            }
            pnlCodeEquipment.Visible = true;
            
            Session["purchaseId"] = _PurchaseInfo.PurchaseId.ToString();
            Session["quantity"] = _PurchaseInfo.Quantity.ToString();

        }
        Session["modelId"] = drlModel.SelectedIndex > 0
                                 ? Int32.Parse(drlModel.SelectedValue)
                                 : Int32.Parse(Resource.EquipModelDefaultId);
        Session["typeId"] = Int32.Parse(drlEquipmentType.SelectedValue);

        Session["companyId"] = Int32.Parse(drlSupplier.SelectedValue.ToString());
        Session["poNumber"] = txtPONumber.Text;
        Session["purchaseDate"] = new Utility().ConvertToCustomizedFormat(txtPurchaseDate.Text);


        pnlWarranty.Visible = true;
        if (!String.IsNullOrEmpty(Session["purchaseId"].ToString()))
        {
            chkSetAutoCode.Checked = true;
            GenerateAvailableCodeNumbers(Int32.Parse(Session["quantity"].ToString()));
            InitializeData(Int32.Parse(Session["quantity"].ToString()));
        }
        lblInformation.Text = "Purchase order has been saved successfully, go to next tab for next steps !";
    }

    private  void GenerateTypeModel()
    {
        int typeId = drlEquipmentType.SelectedIndex > 0
                         ? Int32.Parse(drlEquipmentType.SelectedValue)
                         : Int32.Parse(Resource.EquipSystemTypeDefaultId);

        int modelId = drlModel.SelectedIndex >= 0
                         ? Int32.Parse(drlModel.SelectedValue)
                         : Int32.Parse(Resource.EquipModelDefaultId);

        EquipmentTypeModel typeModel = _ReferenceDataService.GetEquipmentTypeModel(typeId,modelId);

        if (typeModel == null )
        {
            typeModel = new EquipmentTypeModel();
            typeModel.ModelId = modelId;
            typeModel.TypeId = typeId;
            _ReferenceDataService.InsertEquipmentTypeModel(typeModel);
        }
       
        
    }
    private EquipmentTypeSystem GenerateTypeSystem()
    {
        int typeId = drlEquipmentType.SelectedIndex > 0
                         ? Int32.Parse(drlEquipmentType.SelectedValue)
                         : Int32.Parse(Resource.EquipSystemTypeDefaultId);

        int systemId = _ReferenceDataService.GetDefaultSystemId();

        EquipmentTypeSystem typeSystem = _ReferenceDataService.GetEquipmentTypeSystem(typeId, systemId);

        if (typeSystem == null)
        {
            typeSystem = new EquipmentTypeSystem();
            typeSystem.SystemId = systemId;
            typeSystem.EquipmentTypeId = typeId;
            _ReferenceDataService.InsertEquipmentTypeSystem(typeSystem);
        }
        return typeSystem;

    }
    
    public int GetTypeId()
    {
        return !String.IsNullOrEmpty(Request.QueryString["typeId"])
                       ? Int32.Parse(Request.QueryString["typeId"]) : 0;
    }
   
    public string GetAttachedParameters()
    {
        string param = string.Empty;
        if (!chkSparepart.Checked)
        {
            param = "quantity=" + (!String.IsNullOrEmpty(txtQuantity.Text) ? Int32.Parse(txtQuantity.Text) : 0) +
                    "&companyId=" + Session["companyId"] +
                    "&modelId=" + Session["ModelId"] +
                    "&purchaseDate=" + Session["purchaseDate"] +
                    "&poNumber=" + Session["poNumber"] +
                    "&equipmentId=" + equipmentId +
                    "&purchaseId=" + Session["purchaseId"];
        }
        else
            param = "quantity=" + (!String.IsNullOrEmpty(txtQuantity.Text) ? Int32.Parse(txtQuantity.Text) : 0) +
                    "&modelId=" + Session["ModelId"]+
                       "&typeId=" + Session["typeId"] +
                       "&companyId=" + Session["companyId"] +
                       "&purchaseDate=" + Session["purchaseDate"] +
                       "&poNumber=" + Session["poNumber"] +
                        "&purchaseId=" + Session["purchaseId"] +
                        "&quantity=" + (!String.IsNullOrEmpty(txtQuantity.Text) ? Int32.Parse(txtQuantity.Text) : 0) +
                        "&sparepart=true"
                        ;

        return param;
    }
    public int GetPurchaseId()
    {
        return Session["purchaseId"] != null ? Int32.Parse(Session["purchaseId"].ToString()):0  ;
    }
    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                           ?
                               Int32.Parse(Request.QueryString["tabIndex"])
                           : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }
        return tabIndex;
    }

    private bool ValidateData()
    {
        if (drlModel.SelectedIndex ==  -1)
        {
            lblRequiredModel.Text = Resource.MessInformSelectAValue;
            lblRequiredModel.Visible = true;
            return false;
        }
        lblRequiredModel.Visible = false;

        if (drlSupplier.SelectedIndex == 0)
        {
            lblRequiredCompany.Text = Resource.MessInformSelectAValue;
            lblRequiredCompany.Visible = true;
            return false;
        }
        lblRequiredCompany.Visible = false;
        if (txtPONumber.Text == string.Empty)

        {
            lblRequiredPO.Text = Resource.MsgFillInformation;
            lblRequiredPO.Visible = true;
            return false;
        }
        lblRequiredPO.Visible = false;
        if (String.IsNullOrEmpty(txtPurchaseDate.Text) || (txtPurchaseDate.Text == ""))
        {
            lblRequiredPurchaseDate.Text = Resource.MsgFillInformation;
            lblRequiredPurchaseDate.Visible = true;
            return false;
        }
        lblRequiredPurchaseDate.Visible = false;

        if (txtUnitPrice.Text == string.Empty)
        {
            lblRequiredUP.Text = Resource.MsgFillInformation;
            lblRequiredUP.Visible = true;
            return false;
        }
        lblRequiredUP.Visible = false;

        if(txtQuantity.Text == string.Empty)
        {
            lblRequiredQuantity.Text = Resource.MsgFillInformation;
            lblRequiredQuantity.Visible = true;
            return false;
        }
        lblRequiredQuantity.Visible = false;
       
       
        return true;
    }
    private EquipPurchaseInfo GetEquipPurchaseInfo()
    {
        EquipPurchaseInfo equipmentPurchaseInfo = new EquipPurchaseInfo();

        equipmentPurchaseInfo.CompanyId = Int32.Parse(drlSupplier.SelectedValue.ToString());
        equipmentPurchaseInfo.POReferenceNumber = txtPONumber.Text;
        equipmentPurchaseInfo.PurchaseDate = new Utility().ConvertToCustomizedFormat(txtPurchaseDate.Text);
        equipmentPurchaseInfo.PurchaseDescription = txtPurchaseDescription.Text;
        equipmentPurchaseInfo.Quantity = !String.IsNullOrEmpty(txtQuantity.Text) ? Int32.Parse(txtQuantity.Text) : 0;
        equipmentPurchaseInfo.UnitPrice = !String.IsNullOrEmpty(txtUnitPrice.Text) ? float.Parse(txtUnitPrice.Text) : 0;
        equipmentPurchaseInfo.StartDate = DateTime.Parse(Resource.EmptylDateTime);
        equipmentPurchaseInfo.HaveId = Int32.Parse(Resource.HaveDefaultId);
        equipmentPurchaseInfo.IsWarranty = false;
       

        return equipmentPurchaseInfo;

    }
    private SparepartPurchaseInfo GetSparePartPurchaseInfo()
    {
        SparepartPurchaseInfo equipmentPurchaseInfo = new SparepartPurchaseInfo();
        equipmentPurchaseInfo.CompanyId = Int32.Parse(drlSupplier.SelectedValue.ToString());
        equipmentPurchaseInfo.POReferenceNumber = txtPONumber.Text;
        equipmentPurchaseInfo.PurchaseDate = new Utility().ConvertToCustomizedFormat(txtPurchaseDate.Text);
        equipmentPurchaseInfo.SparepartPurchaseInfoDesc = txtPurchaseDescription.Text;
        equipmentPurchaseInfo.Quantity = !String.IsNullOrEmpty(txtQuantity.Text) ? Int32.Parse(txtQuantity.Text) : 0;
        equipmentPurchaseInfo.UnitPrice = !String.IsNullOrEmpty(txtUnitPrice.Text) ? float.Parse(txtUnitPrice.Text) : 0;
        equipmentPurchaseInfo.StartDate = DateTime.Parse(Resource.EmptylDateTime); ;
        equipmentPurchaseInfo.EndDate = DateTime.Parse(Resource.EmptylDateTime);
        // for have table 
        EquipmentTypeSystem typeSystem  = GenerateTypeSystem();
        equipmentPurchaseInfo.HaveId = typeSystem.EquipmentTypeSystemId;
        return equipmentPurchaseInfo;

    }
    private Sparepart GetSparePart(int sparepartPurchaseInfoId)
    {
        int modelId = drlModel.SelectedIndex >= 0
                         ? Int32.Parse(drlModel.SelectedValue)
                         : Int32.Parse(Resource.EquipModelDefaultId);
        Sparepart equipmentPurchaseInfo = new Sparepart();
        equipmentPurchaseInfo.ModelId = modelId;
        equipmentPurchaseInfo.InformationId = sparepartPurchaseInfoId;
        equipmentPurchaseInfo.IsDamaged = false;

        return equipmentPurchaseInfo;

    }
    
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Session["defaultTabIndex"] = 0;
        Response.Redirect("EquipmentAdd2.aspx?"+GetAttachedParameters());
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("./EquipmentDisplay.aspx");
    }
    
    protected void drlEquipmentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["defaultTabIndex"] = 0;
        if (drlEquipmentType.SelectedIndex >= 0)
        {
            drlModel.DataSource = new DirectService().GetEquipmentModelByType(Int32.Parse(drlEquipmentType.SelectedValue));
            drlModel.DataValueField =  "MODELID";
            drlModel.DataTextField =  "MODEL";
            drlModel.DataBind();
        }
        else drlModel.DataSource = null;
        
    }
    protected void chkSparepart_CheckedChanged(object sender, EventArgs e)
    {
        Session["defaultTabIndex"] = 0;
        drlEquipmentType.DataSource = _ReferenceDataService.GetEquipmentTypes(chkSparepart.Checked);
        drlEquipmentType.DataValueField = Resource.EquipmentTypeValueField;
        drlEquipmentType.DataTextField = Resource.EquipmentTypeTextField;
        drlEquipmentType.DataBind();
       

    }
    protected void drlModel_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void btnValidateCodeNumber_Click(object sender, EventArgs e)
    {
        // insert base on the number of purchase order
        Session["defaultTabIndex"] = 2;
        if (!String.IsNullOrEmpty(txtQuantity.Text))
        {

            if (chkSetAutoCode.Checked)
            {
                //Request IList of code number  = purchase quantity


                IList codeNumberList = GetSuggestedCodeNumber();
                for (int i = 0; i < Int32.Parse(txtQuantity.Text); i++)
                {
                    if (!chkSparepart.Checked)
                    {
                        Equipment equipment = new Equipment();
                        equipment.EquipmentId = 0;
                        equipment.ModelId = Int32.Parse(Session["modelId"].ToString());
                        equipment.PurchaseId = Int32.Parse(Session["purchaseId"].ToString());
                        equipment.EstimatedEOL = DateTime.Parse(Resource.DateTimeNull);
                        equipment.CodeNumber = codeNumberList[i].ToString();
                        _StockService.Save(equipment);
                        Session["equipmentId"] = equipment.EquipmentId;
                        
                        // owner , unuse = 1
                        EquipmentOwner owner = new EquipmentOwner();
                        owner.OwnerId = 0;
                        owner.UnUse = false;
                        owner.CodeNumber = equipment.CodeNumber;
                        

                        //set default user  = stockuser whose id  = 186
                        owner.EmployeeId = Int32.Parse(Resource.StockUserDefaultId);
                        owner.DateEnter = DateTime.Parse(Resource.DateTimeNull);
                        owner.SystemId = Int32.Parse(Resource.EquipSystemDefaultId);
                        owner.TypeId = Int32.Parse(Resource.EquipSystemTypeDefaultId);
                        _StockService.InsertEquipmentOwner(owner);
                    }


                }
                btnValidate.Enabled = false;
            }
            else
            {
                Equipment equipment = new Equipment();
                equipment.EquipmentId = 0;
                equipment.ModelId = Int32.Parse(Session["modelId"].ToString());
                equipment.PurchaseId = Int32.Parse(Session["purchaseId"].ToString());
                equipment.EstimatedEOL = DateTime.Parse(Resource.DateTimeNull);
                //equipment.CodeNumber = txtCode.Text;
                _StockService.Save(equipment);
                btnValidate.Enabled = true;
            }
           
        }
    }
    private IList GetSuggestedCodeNumber()
    {
        IList listCodeNumbers = new ArrayList();
        for (int i = 0; i < drlAutoCode.Items.Count;i++ )
        {
            listCodeNumbers.Add(drlAutoCode.Items[i].Text);
          
        } 
        return listCodeNumbers;
    }
    protected void chkIsWarranty_CheckedChanged(object sender, EventArgs e)
    {
        SetVisibleMode();
    }
    private void SetVisibleMode()
    {
        txtContractDescription.Enabled = chkIsWarranty.Checked;
        txtStartDate.Enabled = chkIsWarranty.Checked;
        txtEndDate.Enabled = chkIsWarranty.Checked;
        btnValidate.Enabled = chkIsWarranty.Checked;
    }
    protected void btnValidateWarranty_Click(object sender, EventArgs e)
    {
        
        if (Int32.Parse(Session["purchaseId"].ToString()) !=0)
        {
            if (!chkSparepart.Checked)
            {
                _PurchaseInfo = GetEquipPurchaseInfo(Int32.Parse(Session["purchaseId"].ToString()));
                _StockService.InsertPurchaseInfo(_PurchaseInfo);
            }
            else
            {
                _SparepartInfo = _StockService.GetPurchaseInformation(Int32.Parse(Session["purchaseId"].ToString()));
                _SparepartInfo.StartDate = new Utility().ConvertToCustomizedFormat(txtStartDate.Text);
                _SparepartInfo.EndDate = new Utility().ConvertToCustomizedFormat(txtEndDate.Text);
                _SparepartInfo.IsWarranty = chkIsWarranty.Checked;

            }
            lblInformationWarranty.Text = Resource.MessageValidate;
            Session["defaultTabIndex"] = 2;
            pnlCodeEquipment.Visible = true;

        }
    }
    private EquipPurchaseInfo GetEquipPurchaseInfo(int purchaseId)
    {
        EquipPurchaseInfo equipmentPurchaseInfo = new EquipPurchaseInfo();
        equipmentPurchaseInfo  = _StockService.GetPurchaseInfo(purchaseId);
        equipmentPurchaseInfo.ContractDescription = txtContractDescription.Text;
        equipmentPurchaseInfo.IsWarranty = chkIsWarranty.Checked;
        equipmentPurchaseInfo.StartDate = new Utility().ConvertToCustomizedFormat(txtStartDate.Text);
        equipmentPurchaseInfo.EndDate = new Utility().ConvertToCustomizedFormat(txtEndDate.Text);
        return equipmentPurchaseInfo;
    }
    // sparepart

    private Sparepart GetSparePart(int sparepartPurchaseInfoId,int modelId)
    {
        Sparepart equipmentPurchaseInfo = new Sparepart();
        equipmentPurchaseInfo.ModelId = modelId;
        equipmentPurchaseInfo.InformationId = sparepartPurchaseInfoId;
        equipmentPurchaseInfo.IsDamaged = false;
        return equipmentPurchaseInfo;

    }
    private SparepartPurchaseInfo GetSparePartPurchaseInfo(int typeId, float capacity)
    {
        SparepartPurchaseInfo equipmentPurchaseInfo = new SparepartPurchaseInfo();
        equipmentPurchaseInfo.CompanyId = drlSupplier.SelectedIndex>0  ? Int32.Parse(drlSupplier.SelectedValue):0;
        equipmentPurchaseInfo.POReferenceNumber = txtPONumber.Text;
        equipmentPurchaseInfo.PurchaseDate =(DateTime)Session["purchaseDate"];
        equipmentPurchaseInfo.Quantity = 1;
        equipmentPurchaseInfo.StartDate = DateTime.Parse(Resource.EmptylDateTime); 
        equipmentPurchaseInfo.EndDate = DateTime.Parse(Resource.EmptylDateTime);
        equipmentPurchaseInfo.Capacity = capacity;
        // get haveid, suppose systemid  = 3 (other )
         int defaultSystem = _ReferenceDataDirectService.GetDefaultSystemId();
        EquipmentTypeSystem typeSystem = _ReferenceDataService.GetEquipmentTypeSystem(typeId,defaultSystem );
        if (typeSystem == null)
        {
            typeSystem  = new EquipmentTypeSystem();
            typeSystem.EquipmentTypeId = typeId;
            typeSystem.SystemId = defaultSystem;
            _ReferenceDataService.InsertEquipmentTypeSystem(typeSystem);
            
        }
        
        equipmentPurchaseInfo.HaveId = typeSystem.EquipmentTypeSystemId;
        return equipmentPurchaseInfo;

    }
    private void GenerateTypeModel(int typeId,int modelId)
     {
         EquipmentTypeModel typeModel = _ReferenceDataService.GetEquipmentTypeModel(typeId, modelId);
         if (typeModel == null)
         {
             typeModel = new EquipmentTypeModel();
             typeModel.ModelId = modelId;
             typeModel.TypeId = typeId;
             _ReferenceDataService.InsertEquipmentTypeModel(typeModel);
         }
     }
    
    
    protected void  btnSubmit_Click(object sender, EventArgs e)
{

    //test validatity of spare part 
    // companyID,ponumber 
    if (String.IsNullOrEmpty(txtPONumber.Text)) return;
    if (drlSupplier.SelectedIndex == 0) return;
    EquipmentSparepart equipmentSparepart;
    // add all spare part of computers
    for (int i = 0; i < Int32.Parse(txtQuantity.Text); i++)
    {
        //VGA
        if (drlVGA.SelectedIndex > 0)
        {
            _SparepartInfo = GetSparePartPurchaseInfo(_ReferenceDataService.GetVGAId(),
                                                      !String.IsNullOrEmpty(txtVGA.Text) ? float.Parse(txtVGA.Text) : 0);
             GenerateTypeModel(_ReferenceDataService.GetVGAId(), Int32.Parse(drlVGA.SelectedValue));
             
            _StockService.InsertSparepartInfo(_SparepartInfo);

            equipmentSparepart = GetEquipmentSparepart(_SparepartInfo.SparepartPurchaseInfoId);

            _StockService.SaveEquipmentSparepart(equipmentSparepart);

            _StockService.InsertSparepart(GetSparePart(_SparepartInfo.SparepartPurchaseInfoId, Int32.Parse(drlVGA.SelectedValue)));
        }
        //CPU
        if (drlCPU.SelectedIndex > 0)
        {
            GenerateTypeModel(_ReferenceDataService.GetCPUId(), Int32.Parse(drlCPU.SelectedValue));
            _SparepartInfo = GetSparePartPurchaseInfo(_ReferenceDataService.GetCPUId(),
                                                      !String.IsNullOrEmpty(txtCPU.Text) ? float.Parse(txtCPU.Text) : 0);
            _StockService.InsertSparepartInfo(_SparepartInfo);
            equipmentSparepart = GetEquipmentSparepart(_SparepartInfo.SparepartPurchaseInfoId);

            _StockService.SaveEquipmentSparepart(equipmentSparepart);
            _StockService.InsertSparepart(GetSparePart(_SparepartInfo.SparepartPurchaseInfoId,Int32.Parse(drlCPU.SelectedValue)));
        }
        //HARDISK
        if (drlHardisk.SelectedIndex > 0)
        {
            GenerateTypeModel(_ReferenceDataService.GetHardiskId(), Int32.Parse(drlHardisk.SelectedValue));
            _SparepartInfo = GetSparePartPurchaseInfo(_ReferenceDataService.GetHardiskId(),
                                                      !String.IsNullOrEmpty(txtHardisk.Text)
                                                          ? float.Parse(txtHardisk.Text)
                                                          : 0);
            _StockService.InsertSparepartInfo(_SparepartInfo);
            equipmentSparepart = GetEquipmentSparepart(_SparepartInfo.SparepartPurchaseInfoId);
            _StockService.SaveEquipmentSparepart(equipmentSparepart);
            _StockService.InsertSparepart(GetSparePart(_SparepartInfo.SparepartPurchaseInfoId, Int32.Parse(drlHardisk.SelectedValue)));
        }
               

        //Network
        if (chkNetwork.Checked)
            if (drlNetwork.SelectedIndex > 0)
            {
                GenerateTypeModel(_ReferenceDataService.GetNetworkCardId(), Int32.Parse(drlNetwork.SelectedValue));
                _SparepartInfo = GetSparePartPurchaseInfo(_ReferenceDataService.GetNetworkCardId(),
                                                          !String.IsNullOrEmpty(txtNetwork.Text)
                                                              ? float.Parse(txtNetwork.Text)
                                                              : 0);

                _StockService.InsertSparepartInfo(_SparepartInfo);

                equipmentSparepart = GetEquipmentSparepart(_SparepartInfo.SparepartPurchaseInfoId);
                _StockService.SaveEquipmentSparepart(equipmentSparepart);

                _StockService.InsertSparepart(GetSparePart(_SparepartInfo.SparepartPurchaseInfoId, Int32.Parse(drlNetwork.SelectedValue)));
            }

        //RAm
        if (drlRAM.SelectedIndex > 0)
        {
            GenerateTypeModel(_ReferenceDataService.GetRamId(), Int32.Parse(drlRAM.SelectedValue));
            _SparepartInfo = GetSparePartPurchaseInfo(_ReferenceDataService.GetRamId(),
                                                  !String.IsNullOrEmpty(txtRAM.Text) ? float.Parse(txtRAM.Text) : 0);

            _StockService.InsertSparepartInfo(_SparepartInfo);

            equipmentSparepart = GetEquipmentSparepart(_SparepartInfo.SparepartPurchaseInfoId);
            _StockService.SaveEquipmentSparepart(equipmentSparepart);

            _StockService.InsertSparepart(GetSparePart(_SparepartInfo.SparepartPurchaseInfoId, Int32.Parse(drlRAM.SelectedValue)));
        }
        // insert computer info : ip , name in computer info
        ComputerInfo pc = new ComputerInfo();
        pc.ComputerInfoId = _ReferenceDataDirectService.GetComputerCodeNumberLastId() + 1;
        pc.ComputerName = txtPCName.Text;
        pc.IPAdress = txtIP.Text;
        _StockService.SaveComputerInfo(pc);
        }
        lblPCdetailInformation.Text = Resource.MessageValidate;
       
    }
    private EquipmentSparepart GetEquipmentSparepart(int sparepartPurchaseInfoId)
    {
        EquipmentSparepart equipmentSparepart = new EquipmentSparepart();
        equipmentSparepart.EquipmentId = !String.IsNullOrEmpty(Request.QueryString["equipmentId"])
                                ? Int32.Parse(Request.QueryString["equipmentId"])
                                : 0;
        equipmentSparepart.InformationId = sparepartPurchaseInfoId;
        equipmentSparepart.CreateDate = new Utility().ConvertToCustomizedFormat(Session["purchaseDate"]);
        equipmentSparepart.Description = (string)Session["description"];
        return equipmentSparepart;

    }

    private void SetEnableMode()
    {
        drlNetwork.Enabled = chkNetwork.Checked;
        txtNetwork.Enabled = chkNetwork.Checked;
    }
    protected void chkNetwork_CheckedChanged(object sender, EventArgs e)
    {
        SetEnableMode();
    }
    protected void chkSetAutoCode_CheckedChanged(object sender, EventArgs e)
    {

    }
    protected void btnValidate_Click1(object sender, EventArgs e)
    {
      
       
        if (Int32.Parse(txtQuantity.Text) != 0)
        {

            if (chkSetAutoCode.Checked)
            { 
                //Request IList of code number  = purchase quantity


                IList codeNumberList = GetSuggestedCodeNumber();
                for (int i = 0; i < Int32.Parse(txtQuantity.Text); i++)
                {
                    if (!chkSparepart.Checked)
                    {
                        Equipment equipment = new Equipment();
                        equipment.EquipmentId = 0;
                        equipment.ModelId = Int32.Parse(Session["modelId"].ToString());

                        equipment.PurchaseId = Int32.Parse(Session["purchaseId"].ToString());
                        equipment.EstimatedEOL = DateTime.Parse(Resource.DateTimeNull);
                        equipment.CodeNumber = codeNumberList[i].ToString();
                        _StockService.Save(equipment);
                        // owner , unuse = 1
                        EquipmentOwner owner = new EquipmentOwner();
                        owner.OwnerId = 0;
                        owner.UnUse = false;
                        owner.CodeNumber = equipment.CodeNumber;

                        //set default user  = stockuser whose id  = 186
                        owner.EmployeeId = Int32.Parse(Resource.StockUserDefaultId);
                        owner.DateEnter = DateTime.Parse(Resource.DateTimeNull);
                        owner.SystemId = Int32.Parse(Resource.EquipSystemDefaultId);
                        owner.TypeId = Int32.Parse(Resource.EquipSystemTypeDefaultId);

                        _StockService.InsertEquipmentOwner(owner);
                        Session["defaultTabIndex"] = 3;
                        pnlSparepart.Visible = true;
                    }


                }
                btnValidate.Enabled = false;
            }
            else
            {
                Equipment equipment = new Equipment();
                equipment.EquipmentId = 0;
                equipment.ModelId = Int32.Parse(Session["modelId"].ToString());
                equipment.PurchaseId = Int32.Parse(Session["purchaseId"].ToString());
                equipment.EstimatedEOL = DateTime.Parse(Resource.DateTimeNull);
                //equipment.CodeNumber = txtCode.Text;
                _StockService.Save(equipment);
                btnValidate.Enabled = true;
            }
            lblInformationCodeNumber.Text = Resource.MessageValidate;
           
        }
    }

    private void LoadSoftwareControl()
    {
        lstSoftwares.DataSource = _ReferenceDataService.GetSoftwares();
        lstSoftwares.DataTextField = EquipmentSoftware.CONST_SOFTWARE_LABEL;
        lstSoftwares.DataValueField  = EquipmentSoftware.CONST_SOFTWARE_ID;
        lstSoftwares.DataBind();
    }
    protected void btnValidateSoft_Click(object sender, EventArgs e)
    {
        pnlSoftware.Visible = false;
        Session["defaultTabIndex"] = 4;
        
        //for (int i = 0; i < lstSoftwarePC.Items.Count; i++ )
        //{
        //    EquipmentSoftware software =_ReferenceDataService.GetSoftwareBySoftId(Int32.Parse(lstSoftwarePC.Items[i].Value.ToString()));
        //    ComputerSoftware computerSoftware = new ComputerSoftware();
        //    computerSoftware.License = true;
        //    computerSoftware.SoftwareId = software.SoftwareId;
        //    computerSoftware.Description = "Description";
        //    _StockService.SaveComputerSoftware(computerSoftware);
            
        //}
            
    }
    protected void btnConfirm_Clicked(object sender, EventArgs e)
    {
        pnlConfirm.Visible = false;
        pnlSoftware.Visible = true;
    }

    protected void ImgbtnExport_Clicked(object sender, EventArgs e)
    {
        Session["defaultTabIndex"] = 4;
        GetInsertSoftwareList("ImgbtnExport");
    }
    protected void ImgbtnImport_Clicked(object sender, EventArgs e)
    {
        Session["defaultTabIndex"] = 4;
        GetInsertSoftwareList("ImgbtnImport");
        

    }

    private void GetInsertSoftwareList(string btnName)
    {

        ListBox listSofts = new ListBox(), listSoftPc = new ListBox();
        listSofts.SelectionMode = ListSelectionMode.Multiple;
        listSoftPc.SelectionMode = ListSelectionMode.Multiple;
        
        if(btnName.Equals("ImgbtnImport"))
        {
            listSoftPc = lstSoftwarePC;
            listSofts = lstSoftwares;
        }
        else
        {
            listSoftPc = lstSoftwares;
            listSofts = lstSoftwarePC;
        }
        int counter = 0;
        for (int i = 0; i < listSofts.Items.Count; i++) if (listSofts.Items[i].Selected) counter++;
        itemToInsert = new ListItem[counter];
        counter = 0;
        for (int i = 0; i < listSofts.Items.Count; i++)
        {
            if (listSofts.Items[i].Selected)
            {
                itemToInsert[counter] = listSofts.Items[i];
                counter++;
            }
        }
        for (int i = 0; i < counter; i++)
        {
            listSoftPc.Items.Insert(0, itemToInsert[i]);
            listSofts.Items.Remove(itemToInsert[i]);
        }
        
        lstSoftwarePC.DataSource = itemToInsert;
       }
    
}
